package com.yhy.server.interceptor;

import com.yhy.domain.User;
import com.yhy.server.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 此拦截器用来从Token中获取User 并放入UserHolder的ThreadLocal中方便后续直接使用
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        1.从请求头获取token
        String token = request.getHeader("Authorization");
//        2.判断token是否为空,如为空则相应401状态码并停止访问
        if(StringUtils.isEmpty(token)){
            response.setStatus(401);
            return false;
        }
//        3.将token变为User
        User user = userService.getUserByToken(token);
//        4.如果user为空,则表示未登录
        if(user == null){
            response.setStatus(401);
            return false;
        }
        UserHolder.setUser(user);
        return true;
    }
}
